# !/usr/bin/env python
# -*- coding: utf-8 -*-

"""
__project__ =  'tricker'
__file__    =  'utils.py'
__author__  =  'king'
__time__    =  '2024/5/21 上午9:24'


                              _ooOoo_
                             o8888888o
                             88" . "88
                             (| -_- |)
                             O\  =  /O
                          ____/`---'\____
                        .'  \\|     |//  `.
                       /  \\|||  :  |||//  \
                      /  _||||| -:- |||||-  \
                      |   | \\\  -  /// |   |
                      | \_|  ''\---/''  |   |
                      \  .-\__  `-`  ___/-. /
                    ___`. .'  /--.--\  `. . __
                 ."" '<  `.___\_<|>_/___.'  >'"".
                | | :  `- \`.;`\ _ /`;.`/ - ` : | |
                \  \ `-.   \_ __\ /__ _/   .-` /  /
           ======`-.____`-.___\_____/___.-`____.-'======
                              `=---='
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                       佛祖保佑        永无BUG
"""
import select
import subprocess
import time
import datetime
from subprocess import CompletedProcess

from tricker.common.log import LOG


def wait_resource_become(func, become_status: str, **kwargs):
    LOG.info(f'wait {kwargs} become {become_status}')
    while True:
        status = func(**kwargs)
        if status != become_status:
            LOG.info('sleep 5 seconds')
            time.sleep(5)
        else:
            LOG.info(f'{kwargs} become {become_status}: True')
            time.sleep(3)
            break


def generate_repo(
    repo_file: str = './uos.repo', arch: str = 'amd64', release: str = '1060a'
):
    """
    Generate UOS repositories
    """

    base_url = 'https://cdimage.uniontech.com/server-dev'
    version = release[:-1]
    mini_version = release[-1:]
    base_repos = ['AppStream', 'BaseOS']
    if release == '1060a':
        base_url = (
            f'{base_url}/{version}/{mini_version}/release/'
            f'compose/%(repo)s/$basearch/os'
        )
    if release == '1060e':
        base_url = f'{base_url}/1060u1/e/release/{arch}/%(repo)s'
        base_repos = ['everything']

    with open(repo_file, 'w+') as f:
        for repo in base_repos:
            url = base_url % {'repo': repo}
            f.writelines(
                [
                    f'[UnionTechOS-{repo}] \n',
                    f'name = UnionTechOS {repo} \n',
                    f'baseurl = {url} \n',
                    'enabled = 1 \n',
                    'gpgcheck = 0 \n',
                    'priority = 1 \n',
                    'module_hotfixes=true \n' '\n',
                ]
            )


def formatted_date() -> str:
    return datetime.datetime.now().strftime("%Y-%m-%d.%H:%M:%S")


def execute(command: str):
    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        shell=True,
    )

    while True:
        reads = [process.stdout.fileno(), process.stderr.fileno()]
        ret = select.select(reads, [], [])

        for fd in ret[0]:
            if fd == process.stdout.fileno():
                output = process.stdout.readline()
                if output:
                    LOG.info(output.strip())
            if fd == process.stderr.fileno():
                error = process.stderr.readline()
                if error:
                    LOG.error(error.strip())

        if process.poll() is not None:
            break

    process.wait()


def execute_rpm(root_path: str, options: str):
    execute(f'sudo rpm --dbpath=/var/lib/rpm --root {root_path} {options}')


def execute_chroot(root_path: str, command: str):
    execute(f'sudo -E chroot {root_path} env -u TMPDIR sh -c "{command}"')
